<script src="__PUBLIC__/Static/libs/avalon/avalon.shim.min.js" charset="utf-8"></script>

<div ms-controller="agent-shop-config">
	<form action="" class="form-horizontal" role="form">
	
		<div class="form-group">
			<label class="col-sm-2 control-label">代理商名称为商城标题</label>
			<div class="col-sm-3">
				<input type="checkbox" ms-duplex-checked="agentShopConfig.show_agent_name" ms-attr-value="1" />
			</div>
		</div>
	
		<div class="form-group">
			<label class="col-sm-2 control-label">代理分级数</label>
			<div class="col-sm-3">
				<input type="text" class="form-control" placeholder="请输入代理级数" datatype="*" ms-duplex="agentShopConfig.level" ms-change="levelChange"/>
			</div>
		</div>
		
		<div class="form-group">
			<label class="col-sm-2 control-label">启用代理进货商城<br/>
			<span class="label label-info">代理进货可升级</span>
			</label>
			<div class="col-sm-3" style="padding-top:7px;">
				<input type="checkbox" ms-duplex-checked="agentShopConfig.enabled" ms-attr-value="1" />
			</div>
		</div>
		
		<div class="form-group">
			<label class="col-sm-2 control-label">启用代理分成</label>
			<div class="col-sm-3" style="padding-top:7px;">
				<input type="checkbox" ms-duplex-checked="agentShopConfig.agentNotStock" ms-attr-value="1" />
			</div>
		</div>
		
		<div class="form-group" ms-if="agentShopConfig.agentNotStock">
			<label class="col-sm-2 control-label">代理分成方案
			</label>
			<div class="col-sm-10" style="padding-top:7px;">
				<label ms-repeat-item="rewardModes" class="radio-inline"><input type="radio" ms-duplex-string="agentShopConfig.rewardMode" ms-attr-value="{{ item.value }}">{{ item.name }}</label>
			</div>
		</div>
		
		<div class="form-group" ms-if='agentShopConfig.agentNotStock && agentShopConfig.rewardMode==0'>
			<label class="col-sm-2 control-label">代理分成比例
				<br/><span class="label label-info">设置佣金分成比例(%) 如：50:30:20</span>
			</label>
			<div class="col-sm-4" id="dealer_percent">
				<div class="percent-container">
					<div class="input-group percent-list" ms-repeat-per="agentShopConfig.agent_reward_percent_array">
						<div class="input-group-addon">{{ getLevelName($index) }}</div>
						<input class="form-control" type="text" ms-duplex="per" ms-change="perChange" placeholder="请输入一个1-100之间的数字">
						<div class="input-group-addon">%</div>
					</div>
				</div>
				<div class="input-group percent-list">
					<div class="input-group-addon">总比例必须为 100</div>
					<input type="text" class="form-control reward_percent" readonly="readonly" name="agent_reward_percent" ms-duplex="agentShopConfig['modeConfig'][0]['agent_reward_percent']" />
					<div class="input-group-addon">=</div> 
					<input type="text" class="form-control reward_percent_total" readonly="readonly" name="reward_percent_total" ms-duplex="agentShopConfig.reward_percent_total" />
					<div class="input-group-addon">%</div>
				</div>
			</div>
		</div>
		
		<div class="form-group" ms-if='agentShopConfig.agentNotStock && agentShopConfig.rewardMode==1'>
			<label class="col-sm-2 control-label">代理分成比例</label>
			<div class="col-sm-4" id="dealer_percent">
				<div class="percent-container">
					<!-- 代理二级分佣  -->
					<div ms-repeat-item0="agentShopConfig['modeConfig'][1]['agent_reward_percent']">
						<div ms-repeat-item1="item0" class="input-group percent-list">
							<div class="input-group-addon">{{ getLevelNameTwo($index, $key) }}</div>
							<input class="form-control" type="text" ms-duplex="$val" placeholder="请输入一个1-100之间的数字">
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<div class="form-group" ms-if='agentShopConfig.agentNotStock && agentShopConfig.rewardMode==2'>
			<label class="col-sm-2 control-label">代理分成比例</label>
			<div class="col-sm-4" id="dealer_percent">
				<div class="percent-container">
					<!-- 代理多级分佣  -->
					<div class="input-group percent-list" ms-repeat="agentShopConfig['modeConfig'][2]['agent_reward_percent']">
						<div class="input-group-addon">{{ getLevelNameThree($key) }}</div>
						<input class="form-control" type="text" ms-duplex="$val" placeholder="请输入一个比例">
					</div>
				</div>
			</div>
		</div>
		
		<div class="form-group">
			<label class="col-sm-2 control-label">代理结算方式
			</label>
			<div class="col-sm-10" style="padding-top:7px;">
				<label ms-repeat-item="settleModes" class="radio-inline"><input type="radio" ms-duplex-string="agentShopConfig.settleMode" ms-attr-value="{{ item.value }}">{{ item.name }}</label>
			</div>
		</div>
		
		<!--<div class="form-group">
			<label class="col-sm-2 control-label">培养分佣比例</label>
			<div class="col-sm-3">
				<input type="text" placeholder="培养分佣比例" datatype="*" ms-duplex="agentShopConfig.level" />
			</div>
		</div>-->
		
        <div class="form-group">
            <div class="col-sm-2"></div>
            <div class="col-sm-10">
                <button type="submit" class="btn btn-primary" ms-click="submitForm">提交保存</button>
                <span id="submitMsg" class="label"></span>
            </div>
        </div>
	</form>
</div>

<style type="text/css">
.percent-list {
	margin-bottom : 4px;
}
</style>
<script type="text/javascript">
	var defaultPercent = [
		[100],
		[70, 30],
		[60, 30, 10],
		[50, 25, 15, 10],
		[45, 25, 15, 10, 5]
	];
	function array_fill(j, k) {
		var a = [];
		for(var i=0; i<j; i++) {
			a.push(k);
		}
		return a;
	}
	
	function loop(j, loopTimes, arr, newArray)
	{
	    if (j == arr.length) {
	        newArray = array_fill(j, 0).join(':')
	        return;
	    }
	    while (arr[j]<loopTimes)
	    {
	        newArray[arr[j]] = {};
	        newArray[arr[j]][-1] = array_fill(j+1, 0).join(':');
	        loop(j + 1, loopTimes, arr, newArray[arr[j]]);
	        arr[j]++;
	        if (j + 1 < arr.length) arr[j + 1] = 0;
	    }
	}
	
	function getRewardModelTwoPercent( $level ) {
		$percent = [];
        if ($level) {
        	$percent[0] = {};
        	$percent[0][-1] = "0";
        }
        for ( $i=0; $i<=($level?$level-1:-1); $i++ ) {
            for ( $j=0; $j<$level; $j++ ) { // for ( $j=0; $j<=((($i+1)<$level)?$i+1:$i); $j++ ) {
            	if ( !$percent[$i] ) {
            		$percent[$i] = {};
            	}
                $percent[$i][$j]="0:0";
            }
        }
        return $percent;
	}
	
	function getRewardModelThreePercent( $level ) {
        $arr = array_fill($level, 0);
        $newArray = {};
        function loop($j, $loopTimes, $path)
        {
        	$path = $path ? $path : "";
            if ($j == $arr.length) {
                return;
            }
            while ($arr[$j]<$loopTimes)
            {
                $temp = $path+($path?".":"")+$arr[$j];
                $newArray[$temp] = array_fill($temp.split('.').length, '0').join(':');
                loop($j + 1, $loopTimes, $path+($path?".":"")+$arr[$j]);
                $arr[$j]++;
                if ($j + 1 < $arr.length) $arr[$j + 1] = 0;
            }
        }            
        loop(0, $level);
        return $newArray;
	}
</script>

<script type="text/javascript">
var agentShopConfig = {:json_encode((object)$agentShopConfig)};
	agentShopConfig.reward_percent_total = 0;
	if ( !agentShopConfig['settleMode'] ) {
		agentShopConfig['settleMode'] = 0;
	}
	// 模式一
	agentShopConfig["agent_reward_percent_array"] = agentShopConfig['modeConfig'][0]['agent_reward_percent'].split(":");
	// 模式二
	if ( !agentShopConfig['modeConfig'][1] ) {
		agentShopConfig['modeConfig'][1] = {};
	}
	if ( !agentShopConfig['modeConfig'][1]['agent_reward_percent'] ) {
		agentShopConfig['modeConfig'][1]['agent_reward_percent'] = getRewardModelTwoPercent(3);
	}
	// 模式三
	if ( !agentShopConfig['modeConfig'][2] ) {
		agentShopConfig['modeConfig'][2] = {};
	}
	if ( !agentShopConfig['modeConfig'][2]['agent_reward_percent'] ) {
		agentShopConfig['modeConfig'][2]['agent_reward_percent'] = getRewardModelThreePercent(3);
	}
	
var vm = avalon.define({
	'$id' : 'agent-shop-config',
	'agentShopConfig' : agentShopConfig,
	'rewardModes' : [{'name':'按层级关系树多级分佣', 'value':0}, {'name':'按推荐关系树二级分佣(区分代理等级)', 'value':1}, {'name':'按推荐关系树多级分佣(区分代理等级)', 'value':2}],
	'settleModes' : [{'name':'厂家按期结算', 'value':0}, {'name':'代理手动提现', 'value':1}],
	'getLevelName' : function(i) {
		if ( i*1 ) {
			return "第"+i+"级分成百分比";
		} else {
			return "总厂家分成百分比";
		}
	},
	'getLevelName' : function(i) {
		if ( i*1 ) {
			return "第"+i+"级分成百分比";
		} else {
			return "总厂家分成百分比";
		}
	},
	'getLevelNameTwo' : function(index, key) {
		if( key < 0 ) {
			return (index+1)+"代直接卖出";
		} else {
			return (index+1)+"代发展"+(key*1+1)+"代卖出分佣比例";
		}
	},
	'getLevelNameThree' : function( key ) {
		var str = "";
		var j = (key+"").split(".");
		for( var i = 0; i < j.length; i++) {
			str += (j[i]*1+1)+'级代理';
			if ( i < j.length-1 ) {
				str += '发展';
			} else if ( i == j.length-1) {
				str += '卖出';
			}
		}
		return str;
	},
	'levelChange' : function() {
		// 模式1
		var input = $(this).val()*1+1;
		var l = defaultPercent[input-1];
		if ( defaultPercent.length < input ) {
			var o = l = defaultPercent[defaultPercent.length-1];
			var u = []; for(var i=0; i<l.length; i++) {u.push(l[i]);} l = u;
			for(var i=0; i<input-o.length; i++) {
				l.push(0);
			}
		}
		vm.agentShopConfig.agent_reward_percent_array = l;
		vm.agentShopConfig['modeConfig'][0].agent_reward_percent = l.join(":");
		vm.agentShopConfig.reward_percent_total = vm.calcTotal();
		
		// 模式2二级
		$level = $(this).val()*1;
        vm.agentShopConfig['modeConfig'][1]['agent_reward_percent'] = getRewardModelTwoPercent( $level );
        
		// 模式3多级
		/*var level = $(this).val()*1;
        var arr = array_fill(level,0);
		var $percent = [];
		loop(0, level, arr, $percent);
		vm.agentShopConfig['modeConfig'][2]['agent_reward_percent'] = $percent;*/
		
		// 模式3多级
		$level = $(this).val()*1;
        vm.agentShopConfig['modeConfig'][2]['agent_reward_percent'] = getRewardModelThreePercent( $level );
	},
	'calcTotal' : function() {
		var total = 0;
		$.each(vm.agentShopConfig.agent_reward_percent_array, function(key, val) {
			total += val * 1;
		});
		return total;
	},
	'perChange' : function() {
		vm.agentShopConfig['modeConfig'][0].agent_reward_percent = vm.agentShopConfig.agent_reward_percent_array.join(":");
		vm.agentShopConfig.reward_percent_total = vm.calcTotal();
	},
    'submitForm': function(){
        $btnSubmit = $(this);
        var data = vm.agentShopConfig.$model;
        $.ajax({
        	type:"POST",
        	url:"__CONTROLLER__/saveAgentShopConfig",
        	async:true,
        	data: { 'agentShopConfig' : agentShopConfig },
        	beforeSend: function(){
        	    $btnSubmit.data("value", $btnSubmit.html()).html("<i class='fa fa-spin fa-spinner'></i> 正在提交中……").attr("disabled",true);
        	},
        	success: function(data){
        	  $("#submitMsg").html(data.msg).removeClass().addClass(['label label-success','label label-danger'][data.error]).show().delay(3000).fadeOut('slow');
        	},
        	error: function(error){
        	    $("#submitMsg").html(error).removeClass().addClass("label label-danger");
        	},
        	complete: function(){
        	    $btnSubmit.removeAttr("disabled").html($btnSubmit.data("value"));
        	}
        });
    }
});

$(function() {
	vm.agentShopConfig.reward_percent_total = vm.calcTotal();
});
</script>